package filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "encoding",urlPatterns = "/*")
public class EncodingFilter implements Filter {//解决post请求的乱码问题
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("EncodingFilter.init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("EncodingFilter.doFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //强制将request类型转为子类httpServletRequest，强制转化父类
        String method = httpServletRequest.getMethod();//获得方法是get还是post
        if (method.equalsIgnoreCase("post")){//解决post请求的乱码问题
            httpServletRequest.setCharacterEncoding("UTF-8");
        }
        chain.doFilter(request,response);//先执行下一个过滤器，没有就访问后台资源
    }

    @Override
    public void destroy() {
        System.out.println("EncodingFilter.destroy");
    }
}
